package boerse.CommandProcessor;

import boerse.main.Exceptions.FalseCommandException;
import boerse.main.Exceptions.FalseParametersException;

import java.io.BufferedReader;
import java.io.IOException;

public class CommandScanner {	

	private BufferedReader reader;
	private CommandTypeInfo[] commands;

	public CommandScanner(CommandTypeInfo[] commands ,BufferedReader reader) {
		this.reader = reader;
		this.commands = commands;
	}
	
	public void fillInCommandDesc(CommandDescriptor commandDescriptor) throws FalseCommandException, FalseParametersException {
		try {
			String s = this.reader.readLine().toLowerCase();
			String[] input = s.split(" ");
			Object[] commandAndParams = new Object[input.length];
			
			for (int i = 0; i < commands.length; i++) {
				if (input[0].equals(commands[i].getCmdName())) {
					commandAndParams[0] = commands[i];
					break;
				}
			}
			
			if (commandAndParams[0] == null)
				throw new FalseCommandException();
			
			
			Class<?>[] params = ((CommandTypeInfo) commandAndParams[0]).getParamTypes();
										
			if ((params == null) && (input.length != 1)) {
				throw new FalseParametersException();
			}
			
			 else if((params != null) && (params.length != (input.length - 1))) {
				 throw new FalseParametersException();
			 }
			 else if((params != null) && (input.length > 1)) {
				for (int i = 0; i < params.length; i++) {
					if (params[i].equals(String.class))
						commandAndParams[i+1] = input[i+1];
					else if (params[i].equals(int.class))
						commandAndParams[i+1] = Integer.parseInt(input[i+1]);
					else
						throw new FalseParametersException();
					}
			 } 				
			
			commandDescriptor.setObject(commandAndParams);
			
		} catch (IOException e) {
			throw new FalseCommandException();
		} catch (NumberFormatException e) {
			throw new FalseParametersException();
		}
	}
	
}
